package com.zhb.zhbojbackendjudgeservice.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 用于创建测试程序用到的交换机和队列（只用在程序启动前执行一次）
 */
@Slf4j
@Component
public class InitRabbitMqBean {

    @Value("${spring.rabbitmq.host:localhost}")
    private String host;
    //创建普通交换机
    public static final String EXCHANGE_NAME = "code_exchange";
    // 创建普通队列，随机分配一个队列名称
    public static final String QUEUE_NAME = "code_queue";
    //创建死信交换机，用于接收超时无人处理的消息
   public static final String DEAD_EXANGE_NAME="dead_code_exchange";
    //创建死信队列，与死信交换机绑定关系，保证死信交换机的信息能够传递给死信队列
    public static final String DEAD_QUEUE_NAME="dead_queue";
    @PostConstruct
    public void init() {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(host);
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            //并指定交换机名称和类型，分为fanout,direct,topic
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");
            channel.exchangeDeclare(DEAD_EXANGE_NAME,"direct");
//处理消息队列的消息重试，避免消息积压，可以选用死信队列
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "my_routingKey");
            log.info("消息队列启动成功");
            channel.queueDeclare(DEAD_QUEUE_NAME,true,false,false,null);
            channel.queueBind(DEAD_QUEUE_NAME,DEAD_EXANGE_NAME,"dead_routingKey");
            log.info("死信消息队列启动成功");
        } catch (Exception e) {
            log.error("消息队列启动失败", e);
        }
    }
}
